﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Budget.Silver.OutcomeServiceReference;

namespace Budget.Silver.Model
{
    public class OutcomeOrderModel
    {
        public string CategoryName { get; set; }

        public decimal CategorySum { get; set; }

        public List<OrderModel> Items { get; set; }

        public OutcomeOrderModel()
        {
            Items = new List<OrderModel>();
        }

        public static ICollection<OutcomeOrderModel> CreateOrders(ICollection<OutcomeOrderData> dataOrders)
        {
            var orders = new Collection<OutcomeOrderModel>();
            if (dataOrders != null)
            {
                var groups = dataOrders.GroupBy(o => o.CategoryName);
                foreach (var gr in groups)
                {
                    var model = new OutcomeOrderModel
                                    {
                                        CategoryName = gr.Key,
                                        CategorySum = gr.Sum(o => o.Amount)
                                    };

                    foreach (var orderData in gr)
                    {
                        model.Items.Add(new OrderModel {Id = orderData.Id, ProductName = orderData.Product.Name, Amount = orderData.Amount});
                    }

                    orders.Add(model);
                }
            }
            return orders;
        }
    }
}